﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using Mangox.Common;
using Mangox.Model.MyBusinessDB;
using Mangox.Model.Stock;

namespace Mangox.BLL.Applet
{
    /// <summary>
    /// 朋友圈，圈子
    /// </summary>
    public class MomentsBLL
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";
        private static Dictionary<int, string> anonymity = new Dictionary<int, string>() { { 1, "火星" },{ 2, "金星" },
        { 3, "木星" }, { 4, "水星" }, { 5, "西牛贺州" }, { 6, "东胜神洲" }, { 7, "哈雷彗星" }, { 8, "月球" }, { 9, "地府" },
        { 10, "西天极乐" }, { 11, "凌霄宝殿" } };

        /// <summary>
        /// 下拉分页获取圈子，根据时间优先排序
        /// </summary>
        /// <returns></returns>
        public List<MomentsMsgResult> GetMomentsMessList()
        {
            List<MomentsMsgResult> list = null;
            try
            {
                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    //list = dbContext.T_MomentsMsg.Where(t => t.State == 1).OrderBy(t => t.CreateTime).ToList();

                    //联表查询
                    var temp = from m in db.T_MomentsMsg
                               join u in db.Users
                               on m.Openid equals u.Openid
                               where m.State == 1
                               orderby m.CreateTime descending
                               select new MomentsMsgResult
                               {
                                   UnionId = u.UnionId,
                                   //NickName = string.IsNullOrEmpty(string.IsNullOrEmpty(u.UserName) ? u.NickName : u.UserName) ? "匿名用户" : string.IsNullOrEmpty(u.UserName) ? u.NickName : u.UserName,
                                   NickName = u.NickName,
                                   UserName = u.UserName,
                                   Gender = u.Gender,
                                   //City = string.IsNullOrEmpty(u.City) ? "火星" : u.City,
                                   City = u.City,
                                   Province = u.Province,
                                   
                                    ID = m.ID,
                                    UID = m.UID,
                                    Openid = m.Openid,
                                    MesContent = m.MesContent,
                                    Picture = m.Picture,
                                    Location = m.Location,
                                    CreateTime = m.CreateTime,
                                    State = m.State
                               };
                    list = temp.Take(50).ToList();
                }

                Random r = new Random();
                foreach (var item in list)
                {
                    item.NickName = GetNickName(item.UserName, item.NickName);
                    item.City = GetCity(item.City, r);
                }

            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "GetMomentsMessList fail-{0}", ex);
            }

            return list;
        }

        public static string GetNickName(string UserName, string NickName)
        {
            if (!string.IsNullOrEmpty(UserName))
            {
                return UserName;
            }
            else if (!string.IsNullOrEmpty(NickName))
            {
                return NickName;
            }
            else
            {
                return "匿名用户";
            }
        }

        public static string GetCity(string city, Random r)
        {
            if (string.IsNullOrEmpty(city))
            {
                return anonymity[r.Next(1, anonymity.Count)];
            }
            return city;
        }

        /// <summary>
        /// 查询圈子带评论
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public MomentsMsgComment GetMomentsMsgComment(int id)
        {
            MomentsMsgComment result = new MomentsMsgComment();

            try
            {
                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    //这种写法必须是主键，否则会报错
                    result.MomentsMsg = db.T_MomentsMsg.Find(id);

                    if (result.MomentsMsg != null && result.MomentsMsg.ID > 0)
                    {
                        //获取圈子所属用户
                        result.User = db.Users.Where(u => u.Openid == result.MomentsMsg.Openid).ToList()[0];
                        result.User.City = GetCity(result.User.City, new Random());
                        result.User.NickName = GetNickName(result.User.UserName, result.User.NickName);

                        //获取评论列表
                        result.CommentList = db.T_Comment.Where(c => c.TopicId == result.MomentsMsg.ID).ToList();

                        //查询二级评论
                    }

                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "GetMomentsMess fail-{0}", ex);
            }
            return result;
        }


        public bool AddMomentsMess(T_MomentsMsg model)
        {
            try
            {
                log.InfoFormat("添加圈子信息：" + JsonCommon.ToJson<T_MomentsMsg>(model));

                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    var temp = new T_MomentsMsg()
                    {
                        Openid = model.Openid,
                        MesContent = model.MesContent,
                        Picture = model.Picture,
                        Location = model.Location,
                        CreateTime = DateTime.Now,
                        State = 1
                    };

                    db.T_MomentsMsg.Add(temp);
                    return db.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "AddMomentsMess fail-{0}", ex);
            }
            return false;
        }


        public bool DelMomentsMess(T_MomentsMsg model)
        {
            try
            {
                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    db.T_MomentsMsg.Remove(model);
                    return db.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "DelMomentsMess fail-{0}", ex);
            }
            return false;
        }


    }
}
